#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 4
#define SIZE2 1024
#define SIZE3 30000

void panic(char *message)
{
	perror(message);
	exit(EXIT_FAILURE);
}

int main (int argc, char *argv[])
{
	if(argc==1) {
		char buf[SIZE2];
		while(1) {
			int count= read(0, buf, sizeof(buf));
			write(1, buf, count);
		}
	}
	else if(argv[1][0]=='>') {
		char *file=argv[1]+1;
		int fd= open(file, O_WRONLY | O_TRUNC | O_CREAT, 0666);
		char buf[SIZE2];
		dup2(fd, 1);
		close(fd);
		while(1) {
			int count= read(0, buf, sizeof(buf));
			write(1, buf, count);
		}
	}
	else if(argv[1][0]=='<') {
		char *file= argv[1]+1;
		int fd= open(file, O_RDONLY);
		dup2(fd, 0);
		close(fd);
		char buf[SIZE];
		int count;
		while(1)
		{
			count= read(fd, buf, sizeof(buf));
			if(count==0)
				break;
			write(1, buf, count);
		}
                printf("\n");	
	}
	else {
		char *file= argv[1];
		int fd= open(file, O_RDONLY);
		char buf[SIZE];
		while(1) {
			int count= read(fd, buf, sizeof(buf));
			if(count==0)
				break;
			write(1, buf, count);
		}
		close(fd);
	}
	return 0;
}
